import { resType } from "../util/publicType";
import { Toast } from "@ant-design/react-native";

export enum Method {
  get = "GET",
  post = "POST",
  delete = "DELETE",
  put = "PUT"
}

const baseUrl = "http://172.16.14.187:3001/api/front";
// 封装请求
const request = <T>(url: string, method: Method, body?: T) => {
  return new Promise(async (resolve:(r:resType)=>void, reject:(r:resType)=>void) => {
    try {
      let res: any = await fetch(baseUrl + url, {
        method,
        headers: {
          'Accept': "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(body),
      });
      res = await res.json();
      const { code } = res.data;
      if (code > 201) {
        Toast.fail({
          content:res.msg,
          mask:true,
          stackable:true
        })
        reject(res)
      }
      return resolve(res.data as resType);
    } catch (err: any) {
      Toast.fail({
        content:'服务不可用',
        mask:true,
        stackable:true
      })
    }
  });
};

export default request;
